import os
import yaml

from global_conf import config


class ElementYamlUtils:
    """获取元素"""

    def __init__(self, name):

        self.file_name = '%s.yaml' % name
        self.element_path = os.path.join(config.ELEMENT_PATH, self.file_name)
        self.elements = {}
        if not os.path.exists(self.element_path):
            raise FileNotFoundError("%s 文件不存在！" % self.element_path)
        with open(self.element_path, encoding='utf-8') as f:
            self.data = yaml.safe_load(f)

        for key in self.data.keys():

            ele = Element(self.data[key]['element_name'],self.data[key]['locator_type'],self.data[key]['locator_value'],self.data[key]['timeout'])
            self.elements[key] = ele

    # __getitem__方法可以使用实例对象['字段名']获取值
    def __getitem__(self, item):
        """获取属性"""
        element = self.elements.get(item)
        if element:
            return element
        raise ArithmeticError("{}中不存在关键字：{}".format(self.file_name, item))


class Element():

    def __init__(self, element_name,locator_type,locator_value,timeout):
        self.__element_name = element_name
        self.__locator_type = locator_type
        self.__locator_value = locator_value
        self.__timeout = timeout
    
    @property
    def element_name(self):
        return self.__element_name

    @element_name.setter
    def element_name(self,element_name):
        self.__element_name = element_name

    @property
    def locator_type(self):
        return self.__locator_type

    @locator_type.setter
    def locator_type(self,locator_type):
        self.__locator_type = locator_type

    @property
    def locator_value(self):
        return self.__locator_value

    @locator_value.setter
    def locator_value(self,locator_value):
        self.__locator_value = locator_value

    @property
    def timeout(self):
        return self.__timeout

    @timeout.setter
    def timeout(self,timeout):
        self.__timeout = timeout

    def __str__(self):

        return "({0},{1})".format(self.__locator_type,self.__locator_value)